package cn.sccdlg.springboot.service.impl;

import cn.sccdlg.springboot.mapper.UserMapper;
import cn.sccdlg.springboot.model.User;
import cn.sccdlg.springboot.servcie.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author RaoShuang
 * @emil 991207823@qq.com
 * @date 2020/4/28 23:29
 */
@Component//spring注解
@Service//dubbo注解
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public List<User> getUserByPage(Map<String, Object> paramMap) {
        return userMapper.selectUserByPage(paramMap);
    }

    @Override
    public int getUserByTqtal() {
        //设置key的序列化方式，采用字符串方式（可读性好）
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //查询redis中缓存的数据分页总条数
        Integer totalRows = (Integer)redisTemplate.opsForValue().get("totalRows");
        if (totalRows == null) {
            //分布式缓存穿透写法，限制直接查询数据库的直连接
            synchronized (this) {
                totalRows = (Integer)redisTemplate.opsForValue().get("totalRows");
                if (totalRows == null) {
                    totalRows = userMapper.selectUserByTqtal();
                    redisTemplate.opsForValue().set("totalRows", totalRows);
                }
            }
        }
        return totalRows;
    }

    @Override
    public int addUser(User user) {
        //设置key的序列化方式，采用字符串方式（可读性好）
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        int addCount = userMapper.insertSelective(user);
        if (addCount > 0) {
            //更新缓存中数据总数
            int totalRows = userMapper.selectUserByTqtal();
            redisTemplate.opsForValue().set("totalRows", totalRows);
        }
        return addCount;
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int deleteUser(Integer id) {
        //设置key的序列化方式，采用字符串方式（可读性好）
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        int delete = userMapper.deleteByPrimaryKey(id);
        if (delete > 0) {
            //更新缓存中数据总数
            int totalRows = userMapper.selectUserByTqtal();
            redisTemplate.opsForValue().set("totalRows", totalRows);
        }
        return delete;
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

}

